/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gbbmgmt;

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.awt.MediaTracker;
import java.net.URL;
import java.util.*;
import java.io.*;
import java.net.MalformedURLException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.applet.Applet;
import javax.imageio.ImageIO;
import java.text.*;



/**
 *
 * @author dchapman
 */
public class PrintSalesOrder {

    // private instance declarations
    private final static int POINTS_PER_INCH = 72;

    //Create Number Formater for displaying numbers.
    public NumberFormat f2 = new DecimalFormat("#0.00");
    public NumberFormat f0 = new DecimalFormat("#0");
    public NumberFormat f3 = new DecimalFormat("#0.000");

    public void PrintSO (){
        //Create a new printer job object.
        PrinterJob printJob = PrinterJob.getPrinterJob();

        //Create a new book and add pages to it
        Book book = new Book();

        //Add the sales order page to the book.
        book.append(new SOPage(), printJob.defaultPage());

        //Tell the printJob to use the Book as the Pageable object.
        printJob.setPageable(book);

        //Show the print dialog box. If user clicks the
        //print button, we then proceed to print, else we cancel
        //the process.
        if (printJob.printDialog()){
            try {
                printJob.print();
            } catch (Exception PrintException){
                PrintException.printStackTrace();
            }
        }
    }

    private class SOPage extends Component implements Printable {

        //this is the class to implement the Sales Order Printing.
        public int print (Graphics g, PageFormat pageFormat, int page){

            //Create the Graphics2D object.
            Graphics2D g2d = (Graphics2D) g;

            //Translate the origin to 0,0 for the top left corner
            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

            //Set the default drawing color to black.
            g2d.setPaint(Color.BLACK);

                        //Print Logos (Logo.JPG and BLogo.JPG
            //Set the URL to the image to load.
            MediaTracker mt = new MediaTracker(this);
            URL imageURL = null;
            URL imageURL2 = null;

            try{
                imageURL = new URL("File:///" + System.getProperty("user.dir") + File.separator + "Logo.JPG");
            } catch (MalformedURLException me){
                me.printStackTrace();
            }
            
            Image image = Toolkit.getDefaultToolkit().getImage(imageURL);
            mt.addImage(image,0);
            try {
                mt.waitForID(0);
            } catch(InterruptedException e){
            }

            try{
                imageURL2 = new URL("File:///" + System.getProperty("user.dir") + File.separator + "BLogo.JPG");
            } catch (MalformedURLException me){
                me.printStackTrace();
            }

            Image image2 = Toolkit.getDefaultToolkit().getImage(imageURL2);
            mt.addImage(image2,1);
            try{
                mt.waitForID(1);
            } catch(InterruptedException e){

            }

            //Render the image on the sheet
            g2d.drawImage (image,0,0,this);

            double imgy = (pageFormat.getImageableHeight() - 100);
            double imgx = (pageFormat.getImageableWidth() - 100);

            //Render second image on sheet.
            g2d.drawImage(image2, (int)imgx, (int)imgy, this);

            //---Section 1 (Header)
            //Print the header
            String titleText = "Grimm Brothers Brewhouse LLC";
            Font titleFont = new Font ("helvetica", Font.BOLD, 18);
            g2d.setFont(titleFont);

            //Comput the right alignment on the page.
            FontMetrics fontMetrics = g2d.getFontMetrics();
            double titleX = (pageFormat.getImageableWidth()) - (fontMetrics.stringWidth(titleText));
            double titleY = 14;
            g2d.drawString (titleText, (int) titleX, (int) titleY);

            //Print the address.
            String addressText0 = "547 N. Denver Ave. Loveland, CO 80537";
            String addressText1 = "970.624.6045";
            String addressText2 = "info@grimmbrosbrewhouse.com";
            Font addressFont = new Font ("helvetica", Font.PLAIN, 12);
            int linespace = 14;
            int addressY = 14;
            g2d.setFont(addressFont);

            //Compute the right alignment for the address info.
            fontMetrics = g2d.getFontMetrics();
            double addressX = (pageFormat.getImageableWidth()) - (fontMetrics.stringWidth(addressText0));
            g2d.drawString (addressText0, (int) addressX, (addressY + (linespace * 1)));
            addressX = (pageFormat.getImageableWidth()) - (fontMetrics.stringWidth(addressText1));
            g2d.drawString (addressText1, (int) addressX, (addressY + (linespace * 2)));
            addressX = (pageFormat.getImageableWidth()) - (fontMetrics.stringWidth(addressText2));
            g2d.drawString (addressText2, (int) addressX, (addressY + (linespace * 3)));

            //Open Database Connection
            DBA.openDBCon();
            //Get Sales Order information.
            DBA.GetSalesOrderData(Global.PrintSalesOrderID);
            //DBA.GetSalesOrderData("7");
            DBA.GetCustomerData(Integer.toString(DBA.SOCust));
            
            long n = DBA.SOId;
            String mask = "i000000";
            String ds = Long.toString(n);
            String z = mask.substring(0,mask.length() - ds.length()) + ds;
            
            //Set up calendar.
            Calendar cal = Calendar.getInstance();
            cal.setTime(DBA.SODate);

            //Add appropriate time to calendar.
            cal.add(Calendar.DATE, DBA.CTerms);
            java.sql.Date due = new java.sql.Date(cal.getTime().getTime());

            //Print Invoice Data:
            String InvoiceNumber = "INVOICE NUMBER: " + z;
            String InvoiceDate = "INVOICE DATE: " + DBA.SODate.toString();
            String InvoiceDue = "DUE DATE: " + due.toString();
            Font invoiceFont = new Font ("helvetica", Font.PLAIN, 12);
            g2d.setFont(invoiceFont);

            //Compute the right alignment for the invoice info.
            fontMetrics = g2d.getFontMetrics();
            double textX = (pageFormat.getImageableWidth()) - (fontMetrics.stringWidth(InvoiceNumber));
            int iY = (addressY + (linespace * 5));
            g2d.drawString (InvoiceNumber, (int) textX, (iY + (linespace * 1)));
            textX = (pageFormat.getImageableWidth()) - (fontMetrics.stringWidth(InvoiceDate));
            g2d.drawString (InvoiceDate, (int) textX, (iY + (linespace * 2)));
            textX = (pageFormat.getImageableWidth()) - (fontMetrics.stringWidth(InvoiceDue));
            g2d.drawString (InvoiceDue, (int) textX, (iY + (linespace * 3)));

            //-- Section 2 (Customer data and invoice)
            //Print Customer Data:
            String CustTo = "TO:";
            String CustName = DBA.CName;
            String CustAddr = DBA.CAddr;
            String CustCSZ = DBA.CCity + ", " + DBA.CState + " " + Integer.toString(DBA.CZip);
            String CustPhone = DBA.CPhone;

            //Calculate Customer Position.
            int cY = 180;
            textX = (fontMetrics.stringWidth(CustTo)+6);
            g2d.drawString(CustTo, 0, (cY + (linespace * 1)));
            g2d.drawString(CustName, (int)textX, (cY + (linespace * 1)));
            g2d.drawString(CustAddr, (int)textX, (cY + (linespace * 2)));
            g2d.drawString(CustCSZ, (int)textX, (cY + (linespace * 3)));
            g2d.drawString(CustPhone, (int)textX, (cY + (linespace * 4)));

            //-- Section 2 Part B List Invoice.
            String SOOUT = DBA.GetSalesOrderString(DBA.SOCSV);
            //SOOUT += "\nTotal Cost: $" + DBA.SOCCost;
            int DateX = 0;
            int ProdX = 75;
            double CostX = pageFormat.getImageableWidth()-ProdX;
            int tY = cY + (linespace * 6);

            //Print out headers of file.
            String TDate = "Date:";
            String TProd = "Product:";
            String TCost = "Cost:";

            g2d.drawString(TDate, DateX, tY);
            g2d.drawString(TProd, ProdX, tY);
            g2d.drawString(TCost, (int)CostX, tY);

            tY += linespace;

            String[] SArry = SOOUT.split("\n");
            for (int i=0; i<SArry.length; i++){
                TDate = DBA.SODate.toString();
                TProd = SArry[i];
                String[] TArry = TProd.split("Cost:");

                g2d.drawString(TDate, DateX, tY);
                g2d.drawString(TArry[0].substring(0,TArry[0].length() - 5), ProdX, tY);
                g2d.drawString(TArry[1], (int)CostX, tY);

                tY += linespace;
            }

            tY += linespace;

            //String TotCost = "$" + Float.toString(DBA.SOCCost);
            String TotCost = "$" + f2.format(DBA.SOCCost);
            String ttl = "Total:";

            double ttlX = pageFormat.getImageableWidth() - ProdX - fontMetrics.stringWidth(ttl) - 5;

            g2d.drawString(TotCost, (int)CostX, tY);
            g2d.drawString(ttl, (int)ttlX, tY);
      
            // -- Section 3 (Footer)
            //Print Contact Info.
            String gContact = "Contact Info:";
            String gBilling = "Billing: Aaron Heaton";
            String gBillingAddr = "aaron@grimmbrosbrewhouse.com";
            String gSales = "Sales: Russell Fruits - 970.480.7325";
            String gSalesAddr = "russell@grimmbrosbrewhouse.com";

            //Compute and display contact info.
            fontMetrics = g2d.getFontMetrics();
            textX = 0;
            double textY = (pageFormat.getImageableHeight()-100);
            linespace = 14;

            g2d.drawString(gContact, (int)textX, (int)textY);
            g2d.drawString(gBilling, (int)textX, ((int)textY + (linespace*2)));
            g2d.drawString(gBillingAddr, (int)textX, ((int)textY + (linespace*3)));
            g2d.drawString(gSales, (int)textX, ((int)textY + (linespace*5)));
            g2d.drawString(gSalesAddr, (int)textX, ((int)textY + (linespace*6)));

            //Close database connection.
            DBA.closeDBCon();

            return (PAGE_EXISTS);
        }

    }

}
